package com.hebo.testdemo.controller;


import com.hebo.testdemo.common.GetId;
import com.hebo.testdemo.model.TFiles;
import com.hebo.testdemo.model.TUser;
import com.hebo.testdemo.service.ITFilesService;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author test
 * @since 2021-08-06
 */
@Controller
@RequestMapping("/files")
public class TFilesController {
    @Autowired
    private ITFilesService itFilesService;

    @PostMapping("uploadFile")
    public String uploadFile(MultipartFile uploadfile, HttpSession session) throws IOException {
        TUser user = (TUser) session.getAttribute("user");

        //原始文件名称
        String oldFilename = uploadfile.getOriginalFilename();
        //获取后缀
        String extension = "." + FilenameUtils.getExtension(uploadfile.getOriginalFilename());
        //新名称
//        String newName = new SimpleDateFormat("yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-", "") + extension;
        //文件大小
        long size = uploadfile.getSize();
        //文件类型
        String contentType = uploadfile.getContentType();

        String localContainer = "/static/files";
        String uploadPath = ResourceUtils.getURL("classpath").getPath() + localContainer;
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        File dateDirPath = new File(uploadPath + File.separator + dateFormat);
        if (!dateDirPath.exists()) {
            dateDirPath.mkdirs();//如果文件不存在就创建
        }
        // 处理文件上传
        uploadfile.transferTo(new File(dateDirPath, oldFilename));
        TFiles tFiles = new TFiles();
        tFiles.setId(55).setOldFileName(oldFilename).setNewFileName(oldFilename)
                .setExt(extension).setUserId(user.getId()).setSize(size+"")
                .setType(contentType).setPath(Paths.get(localContainer, dateFormat, oldFilename).toString());
        itFilesService.saveFile(tFiles);

        return "redirect:/files/findAll";
    }

    @GetMapping("/findAll")
    public String findAll(HttpSession session, Model model) {
        TUser user = (TUser) session.getAttribute("user");
        List<TFiles> allByUserId = itFilesService.findAllByUserId(user.getId());
        model.addAttribute("files", allByUserId);
        return "showAll";
    }



}

